<?php
	class Db_product extends CI_Model{
		public function __construct(){
			parent::__construct();
		}
		
	public function cat_add(){
			if($this->session->userdata('sess_login') == null)
				redirect('apanel');
		}
		
		
	
		
				public function cate_all($subcate=""){
			if($subcate == ""){
				$subcate = 0;
			}
			$config['base_url'] = base_url().'manage_product/cate_list';
 			if($this->session->userdata("sess_customer_name") != "eshine"){
 				$this->db->where("customer_pkid",$this->session->userdata("sess_customer_id"));
 			}
 			$this->db->where("parent_pkid",$subcate);
			$config['total_rows'] = $this->db->count_all_results("mobile_product_category");
			$config['per_page'] = 20;
			$config['full_tag_open'] = '<div class="pages">';
			$config['full_tag_close'] = '<div>';
			$this->pagination->initialize($config);
			$this->db->select("t1.pkid,t1.name_en,t2.name");
			$this->db->from("mobile_product_category t1");
			$this->db->join("mobile_customer t2", "t1.customer_pkid = t2.pkid");
			if($this->session->userdata("sess_customer_name") != "eshine")
				$this->db->where("t2.pkid",$this->session->userdata("sess_customer_id"));
			
			//echo "subcate =".$subcate;
			$this->db->where("t1.parent_pkid",$subcate);
			$this->db->limit($config['per_page'],$this->uri->segment(4));
			$this->db->order_by("t1.pkid", "desc");
			$res = $this->db->get();
			//==
			$no = $this->uri->segment(3)+1;
			$i = 1;
			$arr = $res->result_array();
			$cat = array();
			foreach ($arr as $P){
				if($i %2 == 0)
					$tmp['back']							="#FFFFFF";
				else
					$tmp['back']							="#F4F4F4";
				$i++;
				$tmp['no']							=$no;
				$tmp['pkid']						=$P['pkid'];
				// sub category
				$num = $this->count_subcate($P['pkid']);
				//
				$tmp['name_en']				=$P['name_en'].'     <a href="'.base_url().'manage_product/cate_list/'.$P['pkid'].'">subcate[ '.$num.' ]</a>';
// 				$tmp['name_zh_cn']			=$P['name_zh_cn'];
// 				$tmp['name_th']					=$P['name_th'];
				$tmp['name']						=$P['name'];
				$cat[] = $tmp;
				$no = $no+1;
			}
			//print_r($cat);
			$num_row = $config['total_rows'];
			$pagelink  = $this->pagination->create_links();
			return array($cat,$num_row,$pagelink,$config['total_rows']);
		}
		
		private function count_subcate($id){
			$this->db->where("parent_pkid",$id);
			$num = $this->db->count_all_results("mobile_product_category");
			return $num;
		}
					
					/////////////////////////////////////////////////////////////
					
		
		
		public  function product_item_list(){
			/* ตัวแปร แบบ array เก็บฟิวด์ใน ฐานข้อมูล ต้องตรงกัน กับ จำนวน columns ที่อยู่ในไฟล์ server_side.php ด้วย
			
			 */
			 
			 
			$aColumns = array( 't1.pkid','t1.img','t1.name_en','t1.pkid','t1.pkid');
			/* กำหนด primary key ให้กับคอลัมน์ */
			$sIndexColumn = "t1.pkid";
			/* ชื่อตาราง */
			//$sTable = "mobile_product_item t1 LEFT JOIN mobile_product_category t2  ON t1.category_pkid = t2.pkid";
			if($this->session->userdata("sess_customer_name") != "eshine"){
				
				$customer_pkid = $this->session->userdata("sess_customer_id");
				$sTable = "mobile_product_item t1 LEFT JOIN mobile_product_category t2  ON t1.category_pkid = t2.pkid WHERE t1.customer_pkid =".$customer_pkid."";
			}else{
				$sTable = "mobile_product_item t1 LEFT JOIN mobile_product_category t2  ON t1.category_pkid = t2.pkid";
			}
			
			/*
			 * แบ่งหน้า
			*/
			$sLimit = "";
			if ($this->input->post('iDisplayStart') != ""  && ($this->input->post('iDisplayLength') != '-1' ))
			{
				$sLimit = "LIMIT ".$this->input->post('iDisplayStart') .", ".$this->input->post('iDisplayLength') ;
			}	
			/*
			 * จัดเรียงลำดับ
			*/
			$sOrder = "";
			if ($this->input->post('iSortCol_0') != "" )
			{
				$sOrder = "ORDER BY  ";
				for ( $i=0 ; $i<intval( $this->input->post('iSortingCols')) ; $i++ )
				{
					if ($this->input->post('bSortable_'.intval($this->input->post('iSortCol_'.$i)) ) == "true" )
					{
						$sOrder .= $aColumns[ intval( $this->input->post('iSortCol_'.$i) ) ]."
						".$this->input->post('sSortDir_'.$i) .", ";
					}
				}
					
				$sOrder = substr_replace( $sOrder, "", -2 );
				if ( $sOrder == "ORDER BY" )
				{
					$sOrder = "";
				}
			}
		
		
			$sWhere = "";
			if ($this->input->post('sSearch') != "" && $this->input->post('sSearch') != "" )
			{
				$sWhere = "WHERE (";
				for ( $i=0 ; $i<count($aColumns) ; $i++ )
				{
					$sWhere .= $aColumns[$i]." LIKE '%". $this->input->post('sSearch') ."%' OR ";
				}
				$sWhere = substr_replace( $sWhere, "", -3 );
				$sWhere .= ')';
			}
		
			/* เวลาค้นหาในคอลัมน์  */
			for ( $i=0 ; $i<count($aColumns) ; $i++ )
			{
				if ( $this->input->post('bSearchable_'.$i) != "" && $this->input->post('bSearchable_'.$i) == "true" && $this->input->post('sSearch_'.$i) != '' )
				{
					if ( $sWhere == "" )
					{
						$sWhere = "WHERE ";
					}
					else
					{
						$sWhere .= " AND ";
					}
					$sWhere .= $aColumns[$i]." LIKE '%".$this->input->post('sSearch_'.$i)."%' ";
				}
			}
		
		
			/*
			 *คำสั่ง SQL ดึงข้อมูลออกมาโชว์
			*
			*/
			$sQuery = "
			SELECT SQL_CALC_FOUND_ROWS ".str_replace(" , ", " ", implode(", ", $aColumns))."
			FROM   $sTable
			$sWhere
			$sOrder
			$sLimit
			";
			$rResult = $this->db->query( $sQuery);
		
			/* จำนวนข้อมูลหลังจากค้นหา */
			 $sQuery = "
			 SELECT FOUND_ROWS() as numT
			 ";
			 $rResultFilterTotal = $this->db->query($sQuery) ;
			 $aResultFilterTotal = $rResultFilterTotal->row();
			 $iFilteredTotal = $aResultFilterTotal->numT;
		
			 /*  จำนวนทั้งหมด */
			$sQuery = "
			SELECT COUNT(".$sIndexColumn.") as num
					FROM   $sTable
					";
					$rResultTotal = $this->db->query( $sQuery);
					$aResultTotal = $rResultTotal->row();
					$iTotal = $aResultTotal->num;
		
		
					/*
					* ส่วนการแสดงผล
			*/
			$output = array(
			 "sEcho" => intval($this->input->post('sEcho')),
			 		"iTotalRecords" => $iTotal,
			 		"iTotalDisplayRecords" => $iFilteredTotal,
			 		"aaData" => array()
			 );
		
		
		
			 		foreach ($rResult->result_array()  as $aRow)  //loop ออกมาแสดงข้อมูล
			 		{
			 			$row = array();
			 			for ( $i=0 ; $i<count($aColumns) ; $i++ )
			 			{
			 			if ( $aColumns[$i] == "version" )
			 			{
			 				$row[] = ($aRow[ $aColumns[$i] ]=="0") ? '-' : $aRow[ $aColumns[$i] ];
			 					
			 				}
			 				else if ( $aColumns[$i] != ' ' )
			 				{
			 				if($i == 0){
			 				$row[] = '<input type="checkbox" name="check[]" value="'.$aRow['pkid'].'" />';
			 				}else if($i == 1){
								
				 				$row[] = '<br><img src="'.base_url().'media/product/'.$aRow['img'].'" width="100" height="100">';
			 				}else if($i == 2){
								$this->db->where("product_pkid",$aRow['pkid']);
								$num = $this->db->count_all_results("mobile_product_pic");
			 					$row[] = $aRow['name_en'].' <a href="'.base_url().'manage_product/picture_list/'.$aRow['pkid'].'">picture['.$num.']</a>';
			 				}
			 				else if($i == 3){
				 				$row[] = '
				 				<a href="'.base_url().'manage_product/product_edit/'.$aRow['pkid'].'" >
				 				<img border="0" src="'.base_url().'images/edit-icon.png">
				 				</a>';
			 				}
							else if($i == 4){
				 				$row[] = '
				 				<a href="'.base_url().'manage_product/product_del/'.$aRow['pkid'].'" >
				 				<img border="0" src="'.base_url().'images/delete-icon.png">
				 				</a>';
			 				}
			 					
			 				}
			 			}
			 			$output['aaData'][] = $row;
			 			}
			 			return $output;
					
			 			//	echo json_encode( $output );
			 		}
					
					
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

					

	////////////////////////////////////////////////////////////////////////////////////////////////////////////////	
		
		public function show_cat($group=""){
			
			$this->db->order_by("pkid","desc");
			$res = $this->db->get('mobile_product_category');
			$str = '<option value="">=select category=</option>';
			foreach ($res->result_array() as $P){
				if($group == $P['pkid']){
					$check = 'selected="selected"';
				}else{
					$check = "";
				}
				$str .='<option value="'.$P['pkid'].'" '.$check.'>'.$P['name_en'].'</option>';
			}
			return $str;
		}
		
		public function show_customer($group = ""){
		//	if($group != "")
			if($this->session->userdata("sess_customer_name") != "eshine")
				$this->db->where("pkid",$this->session->userdata("sess_customer_id"));
			$this->db->order_by("pkid","desc");
			$res = $this->db->get('mobile_customer');
			$str = '<option value="">=select partner=</option>';
			foreach ($res->result_array() as $P){
				if($group == $P['pkid']){
					$check = 'selected="selected"';
				}else{
					$check = "";
				}
				$str .='<option value="'.$P['pkid'].'" '.$check.'>'.$P['name'].'</option>';
			}
			return $str;
		}
		
		public function show_cate($group = ""){
		//	if($group != "")

				$this->db->where("name",'huawei');
				$res1 = $this->db->get('mobile_customer');
				$row1 = $res1->row();
			if($row1!=""){
			
			
			$this->db->order_by("pkid","desc");
			$this->db->where("customer_pkid",$row1->pkid);
			$res = $this->db->get('mobile_product_category');
			$str = '<option value="0">=select category=</option>';
			foreach ($res->result_array() as $P){
				if($group == $P['pkid']){
					$check = 'selected="selected"';
				}else{
					$check = "";
				}
				$str .='<option value="'.$P['pkid'].'" '.$check.'>'.$P['name_en'].'</option>';
			}
			return $str;
			}
		}
		
		
		public function show_pro($group = ""){
		//	if($group != "")
			
				$this->db->where("name",'huawei');
				$res1 = $this->db->get('mobile_customer');
				$row1 = $res1->row();
			if($row1!=""){
			
			$this->db->order_by("pkid","desc");
			$this->db->where("customer_pkid",$row1->pkid);
			$this->db->where("category_pkid",0);
			$res = $this->db->get('mobile_product_item');
			$str = '<option value="0">=select product=</option>';
			foreach ($res->result_array() as $P){
				if($group == $P['pkid']){
					$check = 'selected="selected"';
				}else{
					$check = "";
				}
				$str .='<option value="'.$P['pkid'].'" '.$check.'>'.$P['name_en'].'</option>';
			}
			return $str;
		}
		}
		
		public function promotion_all(){
			$config['base_url'] = base_url().'manage_product/promotion_list';
			$config['total_rows'] = $this->db->count_all("hotel_promotion");
			$config['per_page'] = 20;
			$config['full_tag_open'] = '<div class="pages">';
			$config['full_tag_close'] = '<div>';
			$this->pagination->initialize($config);
			$this->db->select('t2.pkid,t2.name_en,t2.img');
			$this->db->from('hotel_product_item t1');
			$this->db->join('hotel_promotion t2', 't1.pkid = t2.product_pkid');
			$this->db->limit($config['per_page'],$this->uri->segment(3));
			$this->db->order_by("t2.pkid", "desc");
			$res = $this->db->get();
			//==
			$no = $this->uri->segment(3)+1;
			$i = 1;
			$arr = $res->result_array();
			$item = array();
			foreach ($arr as $P){
				if($i %2 == 0)
					$tmp['back']							="#FFFFFF";
				else
					$tmp['back']							="#F4F4F4";
				$i++;
				$tmp['no']							=$no;
				$tmp['pkid']						=$P['pkid'];
				$tmp['title_en']					=$P['name_en'];
				if(trim($P['img']) != "")
					$tmp['img']						='<br><img src="'.base_url().'media/product/'.$P['img'].'" width="100" height="100">';
				$item[] = $tmp;
				$no = $no+1;
			}
			$num_row = $config['total_rows'];
			$pagelink  = $this->pagination->create_links();
			return array($item,$num_row,$pagelink,$config['total_rows']);
		}
		
		public function get_script(){
			$str ='<script type="text/javascript" language="javascript">
							jQuery("#g_product").autocomplete("'.base_url().'manage_product/get_product", {
										width: 300,
										selectFirst: true,
										formatItem: function formatItem(row) {
											return row[1] //+ " : " + row[1];
										},
										formatResult: function formatResult(row) {
											return row[1] ;
										}
								});

								jQuery("#g_product").blur(function() {
									//blockUI();
									var id = jQuery("#g_product").val();
									get_product(id);	// ส่งค่าไปเลือกสินค้า							  
								});
								function get_product() {
										var id = jQuery("#g_product").val();
										jQuery.getJSON("'.base_url().'manage_product/get_update_product/" + encodeURIComponent(id), "", put_product_data);
								}
								function put_product_data(data){
									jQuery("#pkid").val(data.pkid);
									jQuery("#code").val(data.codes);
									jQuery("#title_en").val(data.title_en);	
									jQuery("#title_cn").val(data.title_cn);	
									jQuery("#title_th").val(data.title_th);	
									jQuery("#price").val(data.price);	
									jQuery("#point_gain").val(data.point_gain);
									jQuery("#point_spend").val(data.point_spend);
								}
								
								 $(document).ready(function() {
				    					$("#datepicker").datepicker({ dateFormat: "yy-mm-dd" });
				    					$("#datepicker2").datepicker({ dateFormat: "yy-mm-dd" });
    					
  								});
					</script>';
			return $str;
		}
		
		public function transport_all(){
			$config['base_url'] = base_url().'manage_product/transport_list';
			$config['total_rows'] = $this->db->count_all("hotel_transport");
			$config['per_page'] = 20;
			$config['full_tag_open'] = '<div class="pages">';
			$config['full_tag_close'] = '<div>';
			$this->pagination->initialize($config);
			$this->db->limit($config['per_page'],$this->uri->segment(3));
			$this->db->order_by("pkid", "desc");
			$res = $this->db->get('hotel_transport');
			//==
			$no = $this->uri->segment(3)+1;
			$i = 1;
			$arr = $res->result_array();
			$cat = array();
			foreach ($arr as $P){
				if($i %2 == 0)
					$tmp['back']							="#FFFFFF";
				else
					$tmp['back']							="#F4F4F4";
				$i++;
				$tmp['no']							=$no;
				$tmp['pkid']						=$P['pkid'];
				$tmp['name_en']				=$P['name_en'];
				$tmp['name_zh_cn']			=$P['name_zh_cn'];
				$tmp['name_th']					=$P['name_th'];
				$cat[] = $tmp;
				$no = $no+1;
			}
			$num_row = $config['total_rows'];
			$pagelink  = $this->pagination->create_links();
			return array($cat,$num_row,$pagelink,$config['total_rows']);
		}
	}
?>
